<!-- App.vue -->
<template>
  <div class="amap-container">
    <header class="header">
      <h1>高德地图路线规划</h1>
    </header>

    <div class="search-container">
      <!-- 起点搜索框 -->
      <div class="search-box">
        <label class="search-label">起点</label>
        <input
            type="text"
            class="search-input"
            v-model="startKeyword"
            @input="searchPlace('start')"
            placeholder="请输入起点位置" />

        <!-- 起点搜索结果列表 -->
        <div class="search-results" v-show="showStartResults">
          <div
              v-for="(item, index) in startResults"
              :key="'start' + index"
              class="result-item"
              @click="selectPlace(item, 'start')">
            <div class="result-name">{{ item.name }}</div>
            <div class="result-address">{{ item.address }}</div>
          </div>
        </div>
      </div>

      <!-- 终点搜索框 -->
      <div class="search-box">
        <label class="search-label">终点</label>
        <input
            type="text"
            class="search-input"
            v-model="endKeyword"
            @input="searchPlace('end')"
            placeholder="请输入终点位置" />

        <!-- 终点搜索结果列表 -->
        <div class="search-results" v-show="showEndResults">
          <div
              v-for="(item, index) in endResults"
              :key="'end' + index"
              class="result-item"
              @click="selectPlace(item, 'end')">
            <div class="result-name">{{ item.name }}</div>
            <div class="result-address">{{ item.address }}</div>
          </div>
        </div>
      </div>

      <!-- 规划路线按钮 -->
      <button
          class="plan-button"
          @click="calculateRoute"
          :disabled="!startPlace || !endPlace">
        规划路线
      </button>
    </div>

    <!-- 地图容器 -->
    <div id="map-container" ref="mapContainer"></div>

    <!-- 路线信息展示 -->
    <div class="route-info" v-if="routeInfo">
      <div class="route-summary">
        <div class="route-distance">总距离: {{ routeInfo.distance }}公里</div>
        <div class="route-time">预计用时: {{ routeInfo.time }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
export default {
  name: 'MapContainer',
  data() {
    return {
      map: null,           // 地图实例
      AMap: null,          // 高德地图API对象
      placeSearch: null,   // 地点搜索服务
      driving: null,       // 驾车规划服务

      startKeyword: '',    // A点搜索关键词
      endKeyword: '',      // B点搜索关键词

      startResults: [],    // A点搜索结果
      endResults: [],      // B点搜索结果

      showStartResults: false,  // 是否显示A点搜索结果
      showEndResults: false,    // 是否显示B点搜索结果

      startPlace: null,    // 选中的A点
      endPlace: null,      // 选中的B点

      startMarker: null,   // A点标记
      endMarker: null,     // B点标记

      routeInfo: null,     // 路线信息
    }
  },

  mounted() {
    // 在组件挂载后初始化地图
    this.initMap();
  },

  methods: {
    // 初始化地图
    initMap() {
      // 注: 实际开发中需要引入高德地图JS API
      // 这里假设已通过CDN或其他方式引入
      this.AMap = window.AMap;

      if (!this.AMap) {
        console.error('高德地图API未加载');
        return;
      }

      // 创建地图实例
      this.map = new this.AMap.Map(this.$refs.mapContainer, {
        resizeEnable: true,
        zoom: 11,           // 初始缩放级别
        center: [116.397428, 39.90923] // 默认中心点(北京)
      });

      // 初始化地点搜索服务
      this.placeSearch = new this.AMap.PlaceSearch({
        pageSize: 10,       // 每页结果数
        pageIndex: 1,       // 页码
        citylimit: true,    // 是否强制限制在设置的城市内搜索
        autoFitView: true   // 是否自动调整地图视野使结果显示在可视区域内
      });

      // 初始化驾车路线规划服务
      this.driving = new this.AMap.Driving({
        map: this.map,
        panel: false        // 不使用默认路线规划面板
      });
    },

    // 搜索地点
    searchPlace(type) {
      // 确定搜索关键词
      const keyword = type === 'start' ? this.startKeyword : this.endKeyword;

      // 如果关键词为空，则隐藏结果列表
      if (!keyword) {
        if (type === 'start') {
          this.showStartResults = false;
        } else {
          this.showEndResults = false;
        }
        return;
      }

      // 执行搜索
      this.placeSearch.search(keyword, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          const places = result.poiList.pois;

          // 更新对应类型的搜索结果
          if (type === 'start') {
            this.startResults = places;
            this.showStartResults = true;
          } else {
            this.endResults = places;
            this.showEndResults = true;
          }
        } else {
          // 搜索失败处理
          console.error('地点搜索失败:', status);

          if (type === 'start') {
            this.startResults = [];
            this.showStartResults = false;
          } else {
            this.endResults = [];
            this.showEndResults = false;
          }
        }
      });
    },

    // 选择地点
    selectPlace(place, type) {
      if (type === 'start') {
        this.startPlace = place;
        this.startKeyword = place.name;
        this.showStartResults = false;

        // 更新起点标记
        this.updateMarker(place, 'start');
      } else {
        this.endPlace = place;
        this.endKeyword = place.name;
        this.showEndResults = false;

        // 更新终点标记
        this.updateMarker(place, 'end');
      }

      // 如果起点和终点都已选择，自动调整地图视野
      if (this.startPlace && this.endPlace) {
        this.adjustMapView();
      }
    },

    // 更新地图标记
    updateMarker(place, type) {
      const position = [place.location.lng, place.location.lat];

      // 创建或更新标记
      if (type === 'start') {
        if (this.startMarker) {
          this.startMarker.setPosition(position);
        } else {
          this.startMarker = new this.AMap.Marker({
            map: this.map,
            position: position,
            icon: new this.AMap.Icon({
              size: new this.AMap.Size(25, 34),
              image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
              imageSize: new this.AMap.Size(25, 34)
            }),
            title: place.name
          });
        }
      } else {
        if (this.endMarker) {
          this.endMarker.setPosition(position);
        } else {
          this.endMarker = new this.AMap.Marker({
            map: this.map,
            position: position,
            icon: new this.AMap.Icon({
              size: new this.AMap.Size(25, 34),
              image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-blue.png',
              imageSize: new this.AMap.Size(25, 34)
            }),
            title: place.name
          });
        }
      }
    },

    // 调整地图视野以同时显示起点和终点
    adjustMapView() {
      if (!this.startPlace || !this.endPlace) return;

      const startPos = [this.startPlace.location.lng, this.startPlace.location.lat];
      const endPos = [this.endPlace.location.lng, this.endPlace.location.lat];

      const bounds = new this.AMap.Bounds(startPos, endPos);
      this.map.setBounds(bounds);
    },

    // 计算路线
    calculateRoute() {
      if (!this.startPlace || !this.endPlace) {
        alert('请先选择起点和终点');
        return;
      }

      // 清除之前的路线
      this.driving.clear();

      // 设置起点和终点
      const startPos = [this.startPlace.location.lng, this.startPlace.location.lat];
      const endPos = [this.endPlace.location.lng, this.endPlace.location.lat];

      // 计算路线
      this.driving.search(startPos, endPos, { waypoints: [] }, (status, result) => {
        if (status === 'complete') {
          console.log('路线规划成功:', result);

          if (result.routes && result.routes.length > 0) {
            const route = result.routes[0];

            // 提取路线信息
            this.routeInfo = {
              distance: (route.distance / 1000).toFixed(1),  // 路线距离，转为公里并保留一位小数
              time: this.formatDrivingTime(route.time)       // 路线耗时，格式化后显示
            };
          }
        } else {
          console.error('路线规划失败:', result);
          alert('路线规划失败，请重试');
        }
      });
    },

    // 格式化驾车时间
    formatDrivingTime(seconds) {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);

      if (hours > 0) {
        return `${hours}小时${minutes}分钟`;
      } else {
        return `${minutes}分钟`;
      }
    }
  }
}
</script>

<style scoped>
.amap-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
}

.header {
  background-color: #108ee9;
  color: white;
  padding: 15px;
  text-align: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.search-container {
  padding: 15px;
  background-color: white;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.search-box {
  position: relative;
  margin-bottom: 15px;
}

.search-label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

.search-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s;
}

.search-input:focus {
  border-color: #108ee9;
}

.search-results {
  position: absolute;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  z-index: 20;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.result-item {
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.result-item:hover {
  background-color: #f5f5f5;
}

.result-item:last-child {
  border-bottom: none;
}

.result-name {
  font-weight: bold;
  margin-bottom: 3px;
}

.result-address {
  font-size: 14px;
  color: #666;
}

.plan-button {
  width: 100%;
  padding: 12px;
  background-color: #108ee9;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.plan-button:hover {
  background-color: #0e77c0;
}

.plan-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

#map-container {
  flex: 1;
  width: 100%;
}

.route-info {
  padding: 15px;
  background-color: white;
  border-top: 1px solid #eee;
}

.route-summary {
  display: flex;
  justify-content: space-between;
}

.route-distance, .route-time {
  font-size: 16px;
  font-weight: bold;
}
</style>